package telco.provider.manager;

import java.util.Collection;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import swa2012.telco.broker.Broker;
import swa2012.telco.broker.beans.BrokerRegistrationStatus;
import swa2012.telco.broker.beans.BrokerSendMessageStatus;
import swa2012.telco.broker.beans.Client;
import swa2012.telco.broker.beans.Message;
import swa2012.telco.broker.beans.Provider;

public class BrokerManager {
	 
	private static final BrokerManager instance = new BrokerManager();
	private Broker broker = null;
	private boolean REGISTERED = false;
	
	//Constructor
    private BrokerManager() 
    {
    	JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    	factory.setServiceClass(Broker.class);
    	factory.setAddress("https://swa.univie.ac.at/TelcoBroker/BrokerService");
    	broker = (Broker) factory.create();
    }
 
    //Gets the singleton instance of this class
    public static BrokerManager getInstance() 
    {
        return instance;
    }
    
    //Registers at broker and prints the answer of the broker
    public void registerMe()
    {
    	if(REGISTERED == false)
    	{
			BrokerRegistrationStatus reg = broker.registerProvider(ProviderManager.getInstance().getMe());
			
			if(reg == BrokerRegistrationStatus.REGISTRATION_OK) 
			{
				System.err.println("Broker registration successfull!");
				REGISTERED = true;
			}
			else if(reg == BrokerRegistrationStatus.REGISTRATION_ALREADY_REGISTERED) System.err.println("Broker already registered!");
			else if(reg == BrokerRegistrationStatus.REGISTRATION_UNSUCCESSFUL_PING) System.err.println("BROKER UNSUCCESSFUL_PING ERROR! Broker couldn't ping provider");
			else if(reg == BrokerRegistrationStatus.REGISTRATION_ERROR) System.err.println("BROKER REGISTRATION ERROR! Couldn't register to Broker");
			else System.err.println("Don't know what happend!");
    	}
    }
    
    //Deregisters from broker and returns the answer of the broker
    public BrokerRegistrationStatus deregisterMe() {
		REGISTERED = false;
    	return broker.deregisterProvider(ProviderManager.getInstance().getMe());
	}

    //Get the clients connected to the broker
	public Collection<Client> getClients() {
		this.registerMe();
		return broker.listClients();
	}
	
	
	public Collection<Provider> getProviders() {
		return broker.listProviders();
	}

	//Sends a message to the broker
	public BrokerSendMessageStatus sendMessage(Message msg) {
		this.registerMe();
		return broker.sendMessage(msg);
	}
}
